<template>
  <div class="map"></div>
</template>

<script>
export default {
  props: {},
  components: {},
  data() {
    return {
      map: null,
      lng: "",
      lat: "",
    };
  },
  methods: {
    initmap() {
      this.map = new AMap.Map("map");
      AMap.event.addListener(this.map, "click", this.getLnglat);
      this.map.setZoom(20);
      this.getlocation();
    },
    // 获取定位
    getlocation() {
      this.map.plugin("AMap.Geolocation", () => {
        let geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, // 是否使用高精度定位,默认:true
          convert: false,
          showMarker: true,
          panToLocation: true,
          timeout: 100,
          showButton: false,
        });
        geolocation.getCurrentPosition();
        this.map.addControl(geolocation);
        AMap.event.addListener(geolocation, "complete", this.onComplete);
        AMap.event.addListener(geolocation, "error", this.onError);
      });
    },
    // 创建点标记
    createPoint(lng, lat) {
      let marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png",
      });
      this.map.add(marker);
    },

    // 成功的回调
    onComplete(result) {
      let { lat, lng } = result.position;
      this.lat = lat;
      this.lng = lng;
      this.createPoint(lng, lat);
      this.$emit("locationResult", { lat, lng });
    },
    // // 定位失败的回调
    onError(error) {
      console.log(error);
    },
    // 点击地图获取数据
    getLnglat(e) {
      // 先清除坐标点
      this.map.clearMap();
      let { lat, lng } = e.lnglat;
      this.createPoint(lng, lat);
      this.$emit("locationResult", { lat, lng });
    },
  },
  mounted() {
    this.initmap();
  },
  watch: {},
  computed: {},
  filters: {},
};
</script>
<style lang="scss" scoped></style>
